package cn.bookcycle.panda.userweb.controller;

import cn.bookcycle.panda.userweb.constant.URLConstant;
import cn.bookcycle.panda.userweb.pojo.vo.BrokerVO;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class BrokerController extends BaseController{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/listBroker")
    public String listBroker(Model model){
        RestTemplate restTemplate=new RestTemplate();
        JSONObject jsonUser=new JSONObject();
        jsonUser.element("userType","broker");

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
            HttpEntity entity=new HttpEntity(jsonUser.toString(),headers);
            ResponseEntity<List> listEntity=restTemplate.exchange(URLConstant.LIST_USERS, HttpMethod.POST,entity,List.class);
            List<BrokerVO> listBroker=listEntity.getBody();
            model.addAttribute("listBroker",listBroker);
            return "brokerList";
        }catch (Exception e){
            logger.error(e.getMessage());
            return "error";
        }
    }

    @RequestMapping(value = "/showBroker")
    public String showBroker(@Nullable@RequestParam("id")String id, Model model){
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<BrokerVO> brokerEntity=restTemplate.getForEntity(URLConstant.GET_USER_BY_USERID+id,BrokerVO.class);
        BrokerVO brokerVO=brokerEntity.getBody();
        model.addAttribute("brokerVO",brokerVO);
        return "brokerDetail";
    }
    /**
     * 经纪人入住页面
     * @return
     */
    @RequestMapping(value = "/brokerSettle")
    public String brokerSettle(){
        return "broker_settle";
    }

    /**
     * 申请成为经纪人
     * @param name
     * @param idNumber
     * @param field
     * @param category
     * @param introduction
     * @return
     */
    @RequestMapping(value = "/brokerSettlePost",method = RequestMethod.POST)
    @ResponseBody
    public String brokerSettlePost(@RequestParam("name")String name,
                                   @RequestParam("idNumber")String idNumber,
                                   @RequestParam("contact")String contact,
                                   @RequestParam("field")String field,
                                   @RequestParam("category")String category,
                                   @RequestParam("introduction")String introduction,
                                   @RequestParam("photo")MultipartFile photo){
        SSOToken ssoToken= SSOHelper.getSSOToken(request);
        RestTemplate restTemplate=new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        MultiValueMap param=new LinkedMultiValueMap();
        String userId=ssoToken.getId();

        try {
            //先将图片上传到服务器，获取该图片在文件服务下的url
            File result=new File(userId+".jpg");
            FileOutputStream fileOutputStream=new FileOutputStream(result);
            fileOutputStream.write(photo.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            FileSystemResource fileSystemResource=new FileSystemResource(result);
            param.add("file",fileSystemResource);
            param.add("filepath","/images/photo");
            String photourl=restTemplate.postForEntity(URLConstant.URL_UPLOAD_FILE,param,String.class).getBody();
            result.delete();

            //申请成为经纪人
            JSONObject jsonUser=new JSONObject();
            jsonUser.element("id",userId);
            jsonUser.element("name",name);
            jsonUser.element("idNumber",idNumber);
            jsonUser.element("field",field);
            jsonUser.element("category",category);
            jsonUser.element("status",1);
            jsonUser.element("userType","broker");
            jsonUser.element("introduction",introduction);
            jsonUser.element("contact",contact);
            jsonUser.element("photo",photourl);
            jsonUser.element("score",3);
            HttpEntity entity=new HttpEntity(jsonUser.toString(),headers);
            restTemplate.exchange(URLConstant.UPDATE_USER, HttpMethod.PUT,entity,String.class);
            logger.info(userId+":申请成为经纪人，进入待审核状态");
            return "申请成为经纪人，进入待审核状态，1s后跳转";
        }catch (HttpClientErrorException e){
            logger.info(userId+":申请成为经纪人，出现错误");
            return "error";
        }catch (IOException e){
            logger.info(e.getMessage());
            return "error";
        }
    }
}
